var md5=require('md5')//支付的md5
/*公共文件*/
const common={
  // 请求接口,myUrl请求地址，
  // myData请求数据，
  // suMethod成功的回调，逆向返回参数（回调）
  // faiMethod失败的回调
  rq:function(myUrl,myData,suMethod,faiMethod){
    myData.domain='9b418296186a627cb6e1c7bb19c50b42';//域名md5
    //本地接口地址
    // const api='http://192.168.124.10:8088/hsl_tp6/api.php/';
    const api='https://demo.gzhslhr.cn/api.php/';
    wx.request({
      url:api+myUrl,
      method:'POST',
      data:myData,
      header: {
        'content-type': 'json'
      },
      success:res=>{
        suMethod(res);//成功把数据返回出去
      },
      fail(){
        faiMethod(res)//失败提示
      }
    })
  },
  // 请求接口,myUrl请求地址，
  // myData请求数据，
  // promise同步
  rq01:function(myUrl,myData){
    myData.domain='9b418296186a627cb6e1c7bb19c50b42';//域名md5
    //本地接口地址
    // const api='http://192.168.124.10:8088/hsl_tp6/api.php/';
    const api='https://demo.gzhslhr.cn/api.php/';
    return new Promise(function(resolve,reject){
      wx.request({
        url:api+myUrl,
        method:'POST',
        data:myData,
        header: {
          'content-type': 'json'
        },
        success:res=>{
          resolve(res)
        },
        fail(){
          reject(res)
        }
      })
    })  
  },
// 临时文件地址转base64
  fileBase64:function({url,type}){
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath: url, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => {
          //图片
          resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data);
            // resolve('data:application/pdf;base64' + res.data)
        },
        fail: res => reject(res.errMsg)
      })
    })
},
//时间过滤器
  // 返回处理后的值,type为类型
  // 1:2020-11
  // 2:2020-11-01
  // 3:2020-11-01 11:30
  // 4:年龄
timeFilter:function(value, type) {
  var time01 = new Date(value * 1000);
  var nowTime=new Date();
  let D = time01.getFullYear();
  let M = parseInt(time01.getMonth()) + 1;
  let T = time01.getDate();
  let S = time01.getHours();
  let MI=time01.getMinutes();
  if (type == 1) {
    return D + '-' + M;
  } else if (type == 2) {
    return D + '-' + M + '-' + T;
  }else if(type==3){
    return D + '-' + M + '-' + T + ' ' + S + ':' + MI;
  }else if(type==4){
    return nowTime.getFullYear()-D;
  }
},
// 1.正则表达式数字和字母和中文
// 2.为中文
// 3.数字
// 4.邮箱
// 5.手机号码
// 6.特殊符号
  reChEng:function(value,num){
    var reg;
    var reg01 = new RegExp(/^[\u4E00-\u9FA5A-Za-z0-9]+$/);
    var reg02 = new RegExp(/^[\u4e00-\u9fa5]{0,}$/);
    var reg03 = new RegExp(/^[0-9]*$/);
    var reg04 = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/);
    var reg05 = new RegExp(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/);
    var reg06 = new RegExp(/^[\da-zA-Z0-9!@#$%^&*]*$/);
    if(num==1){
      reg=reg01
    }else if(num==2){
      reg=reg02
    }else if(num==3){
      reg=reg03
    }else if(num==4){
      reg=reg04
    }else if(num==5){
      reg=reg05
    }else if(num==6){
      reg=reg06
    }
    if(reg.test(value)){
      return true;
    }else{
      return false;
    }
  },
  // 支付api4封装，统一支付接口
  // 前提再后台允许域名请求
  // https://api.mch.weixin.qq.com/pay/unifiedorder
  unitedPayRequest:function(){
      var that = this;
      //统一支付签名
      var appid = 'wx15b92f26c12153b8';//appid必填
      var body = '12345';//商品名必填,没有编码不能用中文
      var mch_id = '1600349125';//商户号必填
      var openid = wx.getStorageSync('openid');
      var nonce_str = that.randomString();//随机字符串，不长于32位。  
      var notify_url = 'https://demo.gzhslhr.cn/api.php';//通知地址必填
      var total_fee = parseInt(0.01 * 100); //价格，这是一分钱
      var trade_type = "JSAPI";
      var key = 'QkF98WPjQsXPiJmfrb4UchKSPn3YGN0K'; //商户key必填，在商户后台获得
      var out_trade_no = that.randomString1();//自定义订单号必填
      var unifiedPayment = 'appid=' + appid + '&body=' + body + '&mch_id=' + mch_id + '&nonce_str=' + nonce_str + '&notify_url=' + notify_url + '&openid=' + openid + '&out_trade_no=' + out_trade_no + '&total_fee=' + total_fee + '&trade_type=' + trade_type + '&key=' + key;
      console.log("unifiedPayment", unifiedPayment);
      var sign = md5.md5(unifiedPayment).toUpperCase();
      console.log("签名md5", sign);
    
      //封装统一支付xml参数
      var formData = "<xml>";
      formData += "<appid>" + appid + "</appid>";
      formData += "<body>" + body + "</body>";
      formData += "<mch_id>" + mch_id + "</mch_id>";
      formData += "<nonce_str>" + nonce_str + "</nonce_str>";
      formData += "<notify_url>" + notify_url + "</notify_url>";
      formData += "<openid>" + openid + "</openid>";
      formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>";
      formData += "<total_fee>" + total_fee + "</total_fee>";
      formData += "<trade_type>" + trade_type + "</trade_type>";
      formData += "<sign>" + sign + "</sign>";
      formData += "</xml>";
      console.log("formData", formData);
      //统一支付
      wx.request({
        url: 'https://api.mch.weixin.qq.com/pay/unifiedorder', //别忘了把api.mch.weixin.qq.com域名加入小程序request白名单，这个目前可以加
        method: 'POST',
        head: 'application/json',
        data: formData, //设置请求的 header
        success: function (res) {
          console.log("返回商户", res.data);
          var result_code = that.getXMLNodeValue('result_code', res.data.toString("utf-8"));
          var resultCode = result_code.split('[')[2].split(']')[0];
          if (resultCode == 'FAIL') {
            var err_code_des = that.getXMLNodeValue('err_code_des', res.data.toString("utf-8"));
            var errDes = err_code_des.split('[')[2].split(']')[0];
            wx.showToast({
              title: errDes,
              icon: 'none',
              duration: 3000
            })
          } else {
            //发起支付
            var prepay_id = that.getXMLNodeValue('prepay_id', res.data.toString("utf-8"));
            var tmp = prepay_id.split('[');
            var tmp1 = tmp[2].split(']');
            //签名  
            var key = 'QkF98WPjQsXPiJmfrb4UchKSPn3YGN0K';//商户key必填，在商户后台获得
            var appId = 'wx15b92f26c12153b8';//appid必填
            var timeStamp = that.createTimeStamp();
            var nonceStr = that.randomString();
            var stringSignTemp = "appId=" + appId + "&nonceStr=" + nonceStr + "&package=prepay_id=" + tmp1[0] + "&signType=MD5&timeStamp=" + timeStamp + "&key=" + key;
            console.log("签名字符串", stringSignTemp);
            var sign = md5.md5(stringSignTemp).toUpperCase();
            console.log("签名", sign);
            var param = { "timeStamp": timeStamp, "package": 'prepay_id=' + tmp1[0], "paySign": sign, "signType": "MD5", "nonceStr": nonceStr }
            console.log("param小程序支付接口参数", param);
            that.processPay(param);
          }
        },
      })
  },
    /* 小程序支付 */
  processPay:function (param) {
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: param.signType,
      paySign: param.paySign,
      success: function (res) {
        // success
        console.log("wx.requestPayment返回信息", res);
        wx.showModal({
          title: '支付成功',
          content: '您已支付成功',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            } else if (res.cancel) {
            }
          }
        })
      },
      fail: function () {
        console.log("支付失败");
      },
      complete: function () {
        console.log("支付完成(成功或失败都为完成)");
      }
    })
  },
  /* 支付---时间戳产生函数   */
  createTimeStamp:function () {
    return parseInt(new Date().getTime() / 1000) + ''
  },
  /*支付--- 随机数 */
  randomString:function () {
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; //默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < 32; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },
  //支付--- 订单号
  randomString1: function () {
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; //默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < 30; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },
  /*支付--- 获取XML节点信息 */
  getXMLNodeValue:function (node_name, xml) {
    console.log(xml)
    var tmp = xml.split("<" + node_name + ">")
    var _tmp = tmp[1].split("</" + node_name + ">")
    return _tmp[0]
  },
}

// 暴露
module.exports = {
  common:common
}
